package com.letere.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.letere.bean.Result;
import com.letere.service.FileService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLDecoder;

/**
 * @author letere
 * @create 2021-02-09 16:58
 */
@RestController
public class FileController {

    @Autowired
    FileService fileService;

    @ApiOperation("新增（上传）文件")
    @ApiImplicitParam(name = "message", value = "JSON字符串（文章id）", dataType = "String")
    @PostMapping("/addFile")
    public Result addFile(String message, @RequestBody MultipartFile file) {
        try {
            //jackson解析JSON字符串
            ObjectMapper om = new ObjectMapper();
            Integer id = om.readValue(message, Integer.class);

            String url = fileService.addFile(id, file);
            return Result.success(url);
        } catch (Exception e) {
            return Result.failure("图片上传失败！");
        }
    }

    @ApiOperation("删除文件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "message", value = "Json字符串（文章id）", required = true),
            @ApiImplicitParam(name = "fileUrl", value = "文件url地址", required = true)
    })
    @PostMapping("deleteFile")
    public void deleteFile(String message, String fileUrl) throws JsonProcessingException {
        //jackson解析JSON字符串
        ObjectMapper om = new ObjectMapper();
        Integer id = om.readValue(message, Integer.class);

        fileService.deleteFile(id, fileUrl);
    }

    @ApiOperation("获取'关于'文章")
    @GetMapping("/getAbout")
    public Result getAbout() {
        try {
            String content = fileService.getAbout();
            return Result.success(content);
        } catch (IOException e) {
            return Result.failure("文件出现异常，请检查！");
        }
    }

    @ApiOperation("编辑'关于'文章")
    @PostMapping("editAbout")
    public void editAbout(@RequestBody String content) throws IOException {
        content = URLDecoder.decode(content, "utf-8");
        fileService.editAbout(content);
    }
}